<?php
/**
 * Configuracao do autoload
 */
function __autoload($classname){
	
	$basedir = dirname(__FILE__);
	$classname = $classname.'.php';

	if(file_exists($basedir.'//core//'.$classname)){
		require_once($basedir.'//core//'.$classname);
	}
	elseif(file_exists($basedir.'//library//'.$classname)){
		require_once($basedir.'//library//'.$classname);
	}
	elseif(file_exists($basedir.'//helpers//'.$classname)){
		require_once($basedir.'//helpers//'.$classname);
	}	
	elseif(file_exists($basedir.'//interfaces//'.$classname)){
		require_once($basedir.'//interfaces//'.$classname);
	}
	elseif(file_exists($basedir.'//core//commercial//'.$classname)){
		require_once($basedir.'//core//commercial//'.$classname);
	}
	else {
		echo 'Class not found!';
	}
}

#inicia configuracao
Config::loadConfig(); 

if(!Config::getDefine('maintenance')){
	#se controller e action for vazio, mostra pag. inicial
	$key = (isset($_GET['key']) ? $_GET['key'] : 'index/main'); 
	#limpa espacos em branco e passa td pra minusculo
	$key = strtolower(trim($key));
	#quebra url em array para carregar parametros
	$key = explode('/', $key);
	
	$url['controller'] = (isset($key[0]) ? ucwords($key[0]).'Controller' : '');
}
else {
	$url['controller'] = 'MaintenanceController';
}

$url['action']     = (isset($key[1]) ? $key[1] : '');
$url['parameter']  = (isset($key[2]) ? $key[2] : '');

$controller_file = '../controller/'.$url['controller'].'.php';

#se o controlador existe...
if(file_exists($controller_file)){
	require_once($controller_file);
	$app = new $url['controller']();
	
	#se a action esta vazia, redireciona para action {main}
	if($url['action'] == ''){
		$url['action'] = 'main';
	}
	
	#se a action existe, instancia ela e passa o param
	if(method_exists($app, $url['action'])){
		$app->$url['action']($url['parameter']);
	}
	#se a action nao existe
	else {
		$error = new Errors();
		$error->code = '1001';
		$error->obj = $url;
		$error->showError();
	}
	
}
#se o controlador nao existe...
else{
	$error = new Errors();
	$error->code = '1000';
	$error->obj = $url;
	$error->showError();
}


?>